<template>
  <div id="dayProduce">
    <div class="bg-color-black">
      <div class="d-flex pt-2 pl-2">
        <span>
          <icon name="align-left" class="text-icon" />
        </span>
        <span class="fs-xl text mx-2">当日产量总结</span>
      </div>
      <div v-if="true" style="margin-top: 10px">
        <dv-scroll-board :config="config" style="width:580px;height:250px" />
      </div>
      <div v-if="true" style="margin-top: -10px; margin-left: 130px;display: flex;">
        <dv-active-ring-chart :config="config4" style="width:350px;z-index:20;height:350px" />
        <span style="margin-top: 100px; margin-left: -330px;z-index:21;font-size: 20px">废板种类</span>
      </div>
    </div>
  </div>
</template>

<script>
import {yieldCalYield} from '@/api/yield'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat'

dayjs.extend(customParseFormat)

export default {
  components: {
    yieldCalYield
  },
  data() {
    return {
      timing2: null,
      config: {},
      config2: {
        header: ['取样板', '片数', '面积', '占比%'],
        // index: true,
        columnWidth: [300],
        align: ['center', 'center', 'center', 'center'],
        data: [
          ['<span style="color:#37a2da;">取样板 2.0mm[长度:1100]</span>', '2', '5.71', '0.01'],
          ['取样板 2.0mm[长度:1100]', '<span style="color:#32c5e9;">2</span>', '5.71', '0.01'],
          ['<span style="color:#ffdb5c;">小计</span>', '4', '0.57', '0.01'],
          [' ', ' ', ' ', ' ']
        ]
      },
      config3: {
        header: ['废板', '片数', '面积', '占比%'],
        // index: true,
        columnWidth: [300],
        align: ['center'],
        data: [
          ['<span style="color:#37a2da;">订单号# 2.0mm L:2379 W:1298]1等品</span>', '10911', '33692.54', '85.12'],
          ['订单号# 2.0mm L:1298 W:2379]]1等品', '<span style="color:#32c5e9;">850</span>', '2624.75', '6.63'],
          ['抽条落板 2.0mm[长度:377.3m]', '<span style="color:#32c5e9;">850</span>', '2624.75', '6.63'],
          ['清边= 2.0mm', '<span style="color:#32c5e9;">850</span>', '2624.75', '6.63'],
          ['<span style="color:#ffdb5c;">小计</span>', '11761', '36317.29', '91.75'],
          [' ', ' ', ' ', ' ']
        ]
      },
      config4: {},
      config5: {
        data: [
          {
            name: '取样板 占比%',
            value: 0.01
          },
          {
            name: '废板 占比%',
            value: 0.01
          },
          {
            name: '抽条 占比%',
            value: 0.02
          },
          {
            name: '清边 占比%',
            value: 0.01
          }
        ]
      },
      config6: {
        data: [
          {
            name: '取样板 占比%',
            value: 0.01
          },
          {
            name: '废板 占比%',
            value: 0.01
          },
          {
            name: '抽条 占比%',
            value: 0.02
          },
          {
            name: '清边 占比%',
            value: 0.01
          }
        ]
      },
      queryParams: {
        // pageNum: 1,
        // pageSize: 30
      },
      searchTime: ['20240118090100', '20240118150700'],
      currentData: {},
      currentDataTest: {
        'msg': '操作成功',
        'code': 200,
        'data': [
          {
            'searchValue': null,
            'createBy': null,
            'createTime': null,
            'updateBy': null,
            'updateTime': null,
            'remark': null,
            'params': {},
            'id': null,
            'timeStart': '2024-05-10 09:00',
            'timeEnd': '2024-05-10 10:10',
            'specCode': '2440.0*3300.0*5.0*2',
            'loadedContainers': 100.65,
            'level': '2',
            'qty': 50,
            'square': 402.6,
            'percent': 0.22095,
            'reason': null,
            'produceFlag': 1,
            'notes': null,
            'teamGroup': null,
            'bz1': null,
            'bz2': null,
            'bz3': null,
            'bz4': null,
            'bz5': null
          },
          {
            'searchValue': null,
            'createBy': null,
            'createTime': null,
            'updateBy': null,
            'updateTime': null,
            'remark': null,
            'params': {},
            'id': null,
            'timeStart': '2024-05-10 09:00',
            'timeEnd': '2024-05-10 10:10',
            'specCode': '2440.0*3300.0*5.0*3',
            'loadedContainers': 26.169,
            'level': '3',
            'qty': 13,
            'square': 104.676,
            'percent': 0.05745,
            'reason': null,
            'produceFlag': 1,
            'notes': null,
            'teamGroup': null,
            'bz1': null,
            'bz2': null,
            'bz3': null,
            'bz4': null,
            'bz5': null
          },
          {
            'searchValue': null,
            'createBy': null,
            'createTime': null,
            'updateBy': null,
            'updateTime': null,
            'remark': null,
            'params': {},
            'id': null,
            'timeStart': '2024-05-10 09:00',
            'timeEnd': '2024-05-10 10:10',
            'specCode': '2250.0*3300.0*5.0*2',
            'loadedContainers': 282.15,
            'level': '2',
            'qty': 152,
            'square': 1128.6,
            'percent': 0.6194,
            'reason': null,
            'produceFlag': 1,
            'notes': null,
            'teamGroup': null,
            'bz1': null,
            'bz2': null,
            'bz3': null,
            'bz4': null,
            'bz5': null
          },
          {
            'searchValue': null,
            'createBy': null,
            'createTime': null,
            'updateBy': null,
            'updateTime': null,
            'remark': null,
            'params': {},
            'id': null,
            'timeStart': '2024-05-10 09:00',
            'timeEnd': '2024-05-10 10:10',
            'specCode': 'WASTE_1_1250.0*3300.0*5.0*5',
            'loadedContainers': 3.09375,
            'level': '5',
            'qty': 3,
            'square': 12.375,
            'percent': 0.00679,
            'reason': 1,
            'produceFlag': 0,
            'notes': null,
            'teamGroup': null,
            'bz1': '琴键废板落板',
            'bz2': null,
            'bz3': null,
            'bz4': null,
            'bz5': null
          },
          {
            'searchValue': null,
            'createBy': null,
            'createTime': null,
            'updateBy': null,
            'updateTime': null,
            'remark': null,
            'params': {},
            'id': null,
            'timeStart': '2024-05-10 09:00',
            'timeEnd': '2024-05-10 10:10',
            'specCode': 'WASTE_9_1200.0*3300.0*5.0*6',
            'loadedContainers': 1.98,
            'level': '6',
            'qty': 2,
            'square': 7.92,
            'percent': 0.00435,
            'reason': 9,
            'produceFlag': 0,
            'notes': null,
            'teamGroup': null,
            'bz1': '取样台取样',
            'bz2': null,
            'bz3': null,
            'bz4': null,
            'bz5': null
          },
          {
            'searchValue': null,
            'createBy': null,
            'createTime': null,
            'updateBy': null,
            'updateTime': null,
            'remark': null,
            'params': {},
            'id': null,
            'timeStart': '2024-05-10 09:00',
            'timeEnd': '2024-05-10 10:10',
            'specCode': 'SNAP',
            'loadedContainers': 5.80057,
            'level': '5',
            'qty': 5,
            'square': 23.2023,
            'percent': 0.01273,
            'reason': 1,
            'produceFlag': 0,
            'notes': null,
            'teamGroup': null,
            'bz1': '琴键废板落板',
            'bz2': null,
            'bz3': null,
            'bz4': null,
            'bz5': null
          },
          {
            'searchValue': null,
            'createBy': null,
            'createTime': null,
            'updateBy': null,
            'updateTime': null,
            'remark': null,
            'params': {},
            'id': null,
            'timeStart': '2024-05-10 09:00',
            'timeEnd': '2024-05-10 10:10',
            'specCode': 'EDGE_CLEAN',
            'loadedContainers': 35.68064,
            'level': '2',
            'qty': 450,
            'square': 142.72256,
            'percent': 0.07833,
            'reason': 11,
            'produceFlag': 0,
            'notes': null,
            'teamGroup': null,
            'bz1': '清边',
            'bz2': null,
            'bz3': null,
            'bz4': null,
            'bz5': null
          }
        ]
      },
      currentFinalData: {},
      currentOtherData0: {},
      currentOtherData1: {},
      OtherData1: {}, // 清边重箱
      currentOtherData2: {},
      currentOtherData3: {},
      cFinalData: [],
      currentWasteData: {}
    }
  },
  computed: {},
  watch: {
    currentFinalData: {
      handler(newdata) {
        this.config = {
          header: ['成品', '片数', '重箱', '占比%'],
          // index: true,
          columnWidth: [300],
          align: ['center'],
          // 轮播方式 'single'|'page'
          // carousel: 'page',
          // 轮播时间间隔 2000
          waitTime: 4000,
          data: newdata
        }
      },
      immediate: true
      // deep: true
    },
    currentWasteData: {
      handler(newdata) {
        this.config4 = {
          radius: '40%',
          activeRadius: '45%',
          digitalFlopStyle: {
            fontSize: 20,
            marginTop: 20
          },
          data: newdata
        }
      },
      immediate: true
      // deep: true
    }
  },
  mounted() {
    // test
    // this.getYieldCalYield(); // todo base
    // this.timeFn2(); // todo base
  },
  beforeDestroy() {
    clearInterval(this.timing2)
  },
  methods: {
    getYieldCalYield() {
      this.searchTime = this.getSearchTime()
      yieldCalYield(this.addDateRange(this.queryParams, this.searchTime)).then(response => {
        this.currentData = JSON.parse(
          JSON.stringify(
            (this.dataFilter(response.data)) // todo 测试完 取消注释
            // (this.dataFilter(this.currentDataTest.data)) // todo 测试后 需注释
          )
        )
        //  小计计算 先算清边 再算成品 再合成 成品/成品+清边
        this.currentOtherData1 = {} // 清边数据清空
        if (this.currentData.filter(item => item.bz1 === '清边').length > 0) {
          this.currentOtherData1 = JSON.parse(
            JSON.stringify(
              (this.currentData.filter(
                item => item.bz1 === '清边')
              )[0].data
            )
          )
          this.OtherData1 = this.currentOtherData1[0][2]
          console.log('临时需求======test OtherData======', this.OtherData1)
        }
        if (this.currentData.filter(item => item.bz1 === '成品').length > 0) {
          this.cFinalData = JSON.parse(
            JSON.stringify(
              (this.currentData.filter(
                item => item.bz1 === '成品')
              )[0].data
            )
          )
          this.cFinalData.push(this.sumFinalDataOnly(this.cFinalData))
        }
        this.currentOtherData1 = {} // 清边数据清空
        if (this.currentData.filter(item => item.bz1 === '清边').length > 0) {
          this.currentOtherData1 = JSON.parse(
            JSON.stringify(
              (this.currentData.filter(
                item => item.bz1 === '清边')
              )[0].data
            )
          )
          this.cFinalData.push(this.sumOtherDataOnly(this.currentOtherData1, '清边', '#05edff')[0])
        }

        if (this.currentData.filter(item => item.bz1 === '落板').length > 0) {
          this.currentOtherData2 = JSON.parse(
            JSON.stringify(
              (this.currentData.filter(
                item => item.bz1 === '落板')
              )[0].data
            )
          )
          this.cFinalData.push(this.sumOtherDataOnly(this.currentOtherData2, '落板', '#ff0e00')[0])
        }
        // 取样颜色  "rgba(255,165,0)"
        if (this.currentData.filter(item => item.bz1 === '取样').length > 0) {
          this.currentOtherData0 = JSON.parse(
            JSON.stringify(
              (this.currentData.filter(
                item => item.bz1 === '取样')
              )[0].data
            )
          )
          this.cFinalData.push(this.sumOtherDataOnly(this.currentOtherData0, '取样', 'rgba(255,165,0)')[0])
        }

        // console.log("!!!",this.currentData);
        // 损失并入落板
        // if (this.currentData.filter(item => item.bz1 === "损失").length > 0) {
        //     this.currentOtherData3 = JSON.parse(
        //         JSON.stringify(
        //             (this.currentData.filter(
        //                     item => item.bz1 === "损失")
        //             )[0].data
        //         )
        //     );
        //     this.cFinalData.push(this.sumOtherDataOnly(this.currentOtherData3, "损失", "#eeff1f")[0]);
        // }
        this.currentFinalData = this.cFinalData
        this.currentWasteData = (JSON.parse(JSON.stringify(this.currentData)))
          .reduce((acc, cur) => {
            // 废板格式 ['取样','落板','清边','抽条','损失',]
            const wasteArray = ['取样', '落板', '清边', '抽条']
            // let wasteArray = ['取样', '落板', '损失', '清边', '抽条'];
            const found = wasteArray.find(item => item === cur.bz1)
            if (found) {
              const temp = this.sumWasteDataOnly(cur.data, found)
              acc.push(temp)
            }
            return acc
          }, [])
      })
    },
    dataFilter(data) {
      return data.reduce((acc, cur) => {
        cur.bz1 = (cur.bz1) ? (cur.bz1) : ('成品')
        cur.bz1 = (cur.bz1 === '取样台取样') || (cur.bz1 === '气垫桌子取样') || (cur.level === '6') ? ('取样') : (cur.bz1)
        // cur.bz1 = (cur.bz1 === "琴键废板落板") || (cur.bz1 === "手动落板") || (cur.bz1 === "堆垛位弃板") || (cur.bz1.length > 20) ? ("落板") : (cur.bz1);
        cur.bz1 = (cur.bz1 === '琴键废板落板') || (cur.bz1 === '手动落板') || (cur.bz1 === '堆垛位弃板') || (cur.bz1.length > 20) || (cur.level === '5') ? ('落板') : (cur.bz1)
        // cur.bz1 = (cur.bz1 === "堆垛位弃板") || (cur.bz1.length > 20) ? ("损失") : (cur.bz1);
        const found = acc.find(item => item.bz1 === cur.bz1)
        const resultArray = [cur.specCode, cur.qty, Number(cur.loadedContainers.toFixed(2)), cur.percent]
        if (found) {
          found.data.push(this.combineName(resultArray, cur.bz1, cur.specCode, cur.percent))
        } else {
          acc.push({
            bz1: cur.bz1,
            data: [this.combineName(resultArray, cur.bz1, cur.specCode, cur.percent)]
          })
        }
        return acc
      }, [])
    },
    // 成品片规格名称包装
    combineName(arr, bz1, code, percent) {
      if (bz1) {
        switch (bz1) {
          case '取样台取样':
            // console.log("取样台取样");
            break
          case '气垫桌子取样':
            // console.log("清边");
            break
          case '落板':
            // console.log("清边123");
            break
          case '弃板xxx':
            // console.log("清边");
            break
          case '清边':
            break
          case '抽条':
            // console.log("清边");
            break
          case '成品':
            // console.log("成品");
            // 成品 2250.0*3300.0*5.0*2\
            // 订单号# 2.0mm [L:1298 W:2379]1等品
            {
              const codeArr = code.split('*')
              arr[0] = '订单号# ' + codeArr[2] + 'mm [L:' + codeArr[0] + ' W:' + codeArr[1] + '] ' + codeArr[3] + '等品'
              // arr[3] = String(percent * 100) + "%";
              arr[3] = (percent * 100).toFixed(2) + '%'
            }
            break
        }
      } else {
        console.log(arr)
      }
      return arr
    },
    sumFinalDataOnly(data) {
      // 小计颜色替换 #ffdb5c
      return data.reduce((acc, cur) => {
        // acc[1] += cur[1]; // 去掉片数
        acc[2] += cur[2]
        acc[2] = Number(acc[2].toFixed(2))
        acc[3] = (acc[2] / (acc[2] + this.OtherData1) * 100).toFixed(2) + '%'
        return acc
      }, ['<span style="color:#1cff47;">总重箱/总成品率</span>', '', 0, ''])
    },
    sumOtherDataOnly(data, name, color) {
      // console.log(name,data,color);
      // data:[cur.specCode, cur.qty, Number(cur.loadedContainers.toFixed(2)), cur.percent]
      return data.reduce((acc, cur) => {
        acc[0][1] += cur[1]
        acc[0][2] += cur[2]
        acc[0][2] = Number(acc[0][2].toFixed(2))
        acc[1] += cur[3]
        acc[0][3] = (acc[1] * 100).toFixed(2) + '%'
        return acc
      }, [['<span style="color:' + color + ';">' + name + '</span>', 0, 0, ''], 0])
    },
    sumWasteDataOnly(data, name) {
      return data.reduce((acc, cur) => {
        acc.value += cur[2]
        return {name: name, value: Number(acc.value.toFixed(2))}
      }, {name: '', value: 0})
    },
    getDate(hours) {
      const currentDate = new Date()
      const currentYear = currentDate.getFullYear()
      const currentMonth = currentDate.getMonth()
      const currentDay = currentDate.getDate()
      const timeStamp = new Date(
        currentYear,
        currentMonth,
        currentDay,
        0,
        0,
        0
      ).getTime()
      console.log('hours:', hours, 'timeStamp:', timeStamp, 'currentYear:', currentYear, 'currentMonth:', currentMonth, 'currentDay:', currentDay)
      return new Date(timeStamp + hours * 60 * 60 * 1000).getTime()
    },
    getSearchTime() {
      const currentTime = new Date()
      const dateFormatString = 'YYYYMMDDHHmmss'
      const currentTimeHour = currentTime.getHours()
      let beginTime = ''
      let thisEndTime = ''
      // am 早班 9:00-20:59 pm 21:00-8:59
      let formateTimeRange = ''
      if (currentTimeHour !== undefined) {
        if ((currentTimeHour >= 9) && (currentTimeHour < 21)) {
          // 当日早班情况
          formateTimeRange = '090000' // 210100
          beginTime = dayjs(currentTime).format('YYYYMMDD') + formateTimeRange
        } else {
          // 当日晚班情况 查询终止时间是当前晚班起始时间分界线之前
          formateTimeRange = '210000'
          if (currentTimeHour >= 21) {
            // 晚班时间未过0点 分界线是当天 查当前晚班起始时间之前
            beginTime = dayjs(currentTime).format('YYYYMMDD') + formateTimeRange
          } else {
            // 晚班时间过0点 分界线是隔天 日期需要回拨1天
            const lastDayTime = dayjs(currentTime).subtract(1, 'day')
            beginTime = lastDayTime.format('YYYYMMDD') + formateTimeRange
          }
        }
        thisEndTime = dayjs(currentTime).format('YYYYMMDDHHmmss')
      }
      return [beginTime, thisEndTime]
    },
    timeFn2() {
      this.timing2 = setInterval(() => {
        console.log('t3 right 实时2', dayjs(new Date()).format('YYYYMMDDHHmmss'))
        this.getYieldCalYield()
      }, 120000)
    }
  }
}
</script>

<style lang="scss" scoped>
  $box-height: 485px;
  $box-width: 100%;
  #dayProduce {
    padding: 20px 16px 20px 16px;
    height: $box-height;
    width: $box-width;
    border-radius: 5px;

    .bg-color-black {
      padding: 5px;
      height: $box-height - 35px;
      width: $box-width;
      border-radius: 10px;
    }

    .text {
      color: #c3cbde;
    }

    .chart-box {
      margin-top: 16px;
      width: 170px;
      height: 170px;

      .active-ring-name {
        padding-top: 10px;
      }
    }
  }
</style>
